package com.tjh.springbootapi.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.koala.apiprototype.db.BaseService;
import com.koala.apiprototype.utils.security.LoginAttemptLimiter;
import com.koala.apiprototype.utils.security.PasswordUtils;
import com.koala.apiprototype.web.response.ApiException;
import com.koala.apiprototype.web.response.ExceptionCode;
import com.tjh.springbootapi.entity.Sysuser;
import com.tjh.springbootapi.enums.StateEnum;
import com.tjh.springbootapi.mapper.SysuserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 服务类
 * Generated on 2020-03-22
 */
@Service
public class SysuserService extends BaseService<SysuserMapper, Sysuser> {

    @Transactional
    public String saveSysuser(Sysuser sysuser) {
        if (StringUtils.isEmpty(sysuser.getUserName())) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "缺少参数");
        }
        Sysuser isUserNameExit = this.findOneBy("userName", sysuser.getUserName());
        if (isUserNameExit != null) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "账号已存在");
        }
        String resultMsg = "初始密码为：" + sysuser.getUserName() + "123456";
        String defalutPassword = PasswordUtils.md5(sysuser.getUserName() + "123456", sysuser.getUserName());
        sysuser.setPassWord(defalutPassword);
        sysuser.setState(StateEnum.Active);
        mapper.insert(sysuser);
        return resultMsg;
    }

    public Sysuser login(String userName, String password) {
        if (LoginAttemptLimiter.isLocked(userName)) {
            throw new ApiException(ExceptionCode.AccountDisabled.getCode(), "账号已被锁，请" + LoginAttemptLimiter.getAccountLockMinutes() + "分钟后重试");
        }
        Sysuser user = super.findOne(Wrappers.<Sysuser>lambdaQuery().eq(Sysuser::getUserName, userName));

        if (user == null) {
            throw new ApiException(ExceptionCode.UserNotExist);
        }
        if (user.getState() == StateEnum.Inactive) {
            throw new ApiException(ExceptionCode.AccountDisabled);
        }
        //加盐加密
        String encryptedPassword = PasswordUtils.md5(password, userName);
        if (!encryptedPassword.equals(user.getPassWord())) {
            int attemptTimes = LoginAttemptLimiter.recordLoginFailed(userName);
            int remainAttemptTimes = LoginAttemptLimiter.getLoginAttemptLimit() - attemptTimes;
            if (remainAttemptTimes == 0) {
                throw new ApiException(ExceptionCode.AccountDisabled.getCode(), "账号已被锁，请" + LoginAttemptLimiter.getAccountLockMinutes() + "分钟后重试");
            }
            throw new ApiException(ExceptionCode.PasswordIncorrect.getCode(), "密码已错误" + attemptTimes + "次，" + remainAttemptTimes + "次后账号将被锁");
        }
        //登录成功
        return user;
    }

}
